package com.mosband.genecharts.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class EchartsUtil {
    private static String url = "http://localhost:16895";
    private static final String SUCCESS_CODE = "1";


    /**
     * 生成64位图片信息
     * @param option echarts报表 option参数
     * @param width 图片宽
     * @param height 图片高
     */
    public static String generateEchartsBase64(String option, String width, String height) throws Exception {
//        System.out.println("前-option=  "+option);
        String base64 = "";
        if (option == null) return base64;
        //\s表示匹配任何空白字符，包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
        //而"\s+"则表示匹配任意多个上面的字符
        option = option.replaceAll("\\s+", "").replaceAll("\"", "'");
        System.out.println("后-option=  "+option);

        if (width == null) width = "1700";
        if (height == null) height = "600";

        // 将option字符串作为参数发送给echartsConvert服务器
        Map<String, String> params = new HashMap<>();
        params.put("opt", option);
        params.put("width", width);
        params.put("height", height);
        System.out.println("向浏览器发送请求\n"+JSONObject.toJSONString(params));
        String response = HttpUtil.post(url, params, "utf-8");

        // 解析echartsConvert响应
        JSONObject responseJson = JSON.parseObject(response);
        System.out.println("浏览器返回\n"+JSONObject.toJSONString(responseJson));
        String code = responseJson.getString("code");

        // 如果echartsConvert正常返回
        if (SUCCESS_CODE.equals(code)) {
            base64 = responseJson.getString("data");
        } else {
            // 未正常返回
            String string = responseJson.getString("msg");
            throw new RuntimeException(string);
        }
        System.out.println("浏览器-渲染-结束......");
        return base64;
    }

    /**
     * 生成图片
     * @param base64 base64图片信息
     * @param path 图片全路径
     */
    public static void generateImage(String base64, String path) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        try (OutputStream out = new FileOutputStream(path)){
            // 解密
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
        }
    }

}
